package cn.gxa.j229.bug.finance.utils;

/*
 *
 *@author leijun
 *
 *@creating 2020/9/27 16:14
 *
 */

import cn.gxa.j229.bug.finance.pojo.Permission;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName TreeUtils
 * @Description TODO
 * @Author 俊
 * @Date 2020/9/27 16:14
 * @Version 1.0
 */
public class TreeUtils {

    public static List<Permission> getTreeList(List<Permission> entityList) {
        List<Permission> resultList = new ArrayList<>();

        //获取顶层元素集合
        String parentCode;
        for (Permission entity : entityList) {
            parentCode = entity.getPid();
            //顶层元素的parentCode==null或者为0
            if (parentCode == null || "0".equals(parentCode)) {
                resultList.add(entity);
            }
        }

        //获取每个顶层元素的子数据集合
        for (Permission entity : resultList) {
            entity.setChildren(getSubList(entity.getId(), entityList));
        }

        return resultList;
    }

    /**
     * 获取子数据集合
     *
     * @param id
     * @param entityList
     * @return
     */
    private static List<Permission> getSubList(String id, List<Permission> entityList) {
        List<Permission> childList = new ArrayList<>();
        String parentId;

        //子集的直接子对象
        for (Permission entity : entityList) {
            parentId = entity.getPid();
            if (id.equals(parentId)) {
                childList.add(entity);
            }
        }

        //子集的间接子对象
        for (Permission entity : childList) {
            entity.setChildren(getSubList(entity.getId(), entityList));
        }

        //递归退出条件
        if (childList.size() == 0) {
            return null;
        }

        return childList;
    }

}
